//
//  MultiPointOverlayViewController.m
//  MAMapKit
//
//  Created by hanxiaoming on 2017/4/13.
//  Copyright © 2017年 Amap. All rights reserved.
//

#import "MultiPointOverlayViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <FMDB/FMDB.h>
#import "UIView+Utils.h"
#import "TipViewController.h"
#import "Location.h"

@interface MultiPointOverlayViewController ()<MAMapViewDelegate, MAMultiPointOverlayRendererDelegate>
{
    MAMultiPointOverlay *_overlay;
    UIView *bottomView;
    UILabel *nameLabel;
    UILabel *positonlabe;
    MAMultiPointItem *currentSelectCharge;
    double lastSelectChargeTime;//间隔0.1秒，防止隐藏弹框
    BOOL didLocataion;//定位成功后就，不再更新区域
    
}

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic,strong) UILabel *label;

@end

@implementation MultiPointOverlayViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"海量点展示";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(returnAction)];
    
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.delegate = self;
    self.mapView.centerCoordinate=[Location shareLocation].location.coordinate;
    self.mapView.zoomLevel=15;
    [self.view addSubview:self.mapView];
    
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollowWithHeading;
    self.mapView.userLocation.title = @"您的位置在这里";
    
    MAUserLocationRepresentation *represent = [[MAUserLocationRepresentation alloc] init];
    represent.showsAccuracyRing = YES;
    represent.showsHeadingIndicator = YES;
    represent.fillColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:.3];
    represent.strokeColor = [UIColor lightGrayColor];;
    represent.lineWidth = 2.f;
    represent.image = [UIImage imageNamed:@"userPosition"];
    [self.mapView updateUserLocationRepresentation:represent];
    
    
    [self initOverlay];
    self.label=[[UILabel alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height-100, self.view.bounds.size.width, 60)];
    [self.view addSubview:self.label];
    [self addHeadView];
}
-(void)addHeadView{
    

//        UIView *_headView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 64)];
//        _headView.backgroundColor=[UIColor whiteColor];
//        [self.view addSubview:_headView];
//
//        UIButton *backbt=[[UIButton alloc]initWithFrame:CGRectMake(0, 20,80, 44)];
//        [backbt setTitle:@"Back" forState:UIControlStateNormal];
//        [backbt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
//        [backbt addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
//        [_headView addSubview:backbt];

    
        UIButton *bt=[[UIButton alloc]initWithFrame:CGRectMake(0, 20, 100,44)];
        [bt addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
        [bt setTitle:@"规划路线" forState:UIControlStateNormal];
        [bt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
//        [_headView addSubview:bt];
    UIBarButtonItem *rightCunstomButtonView = [[UIBarButtonItem alloc] initWithCustomView:bt];
    self.navigationItem.rightBarButtonItem = rightCunstomButtonView;
    

//       self.navigationItem.rightBarButtonItem = bt;
//    [self.view addSubview:_headView];


}
-(void)goSearch{
    TipViewController *s=[[TipViewController alloc]init];
    [self.navigationController pushViewController:s animated:YES];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)initOverlay
{

    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [path objectAtIndex:0];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MAP" ofType:@"db"];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:@"MAP.db"];
    NSLog(@"%@",filePath);
    if(![[NSFileManager defaultManager]fileExistsAtPath:dstPath]){
        [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:dstPath error:nil];
    }
    //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:dstPath];
    
    NSMutableArray *items = [NSMutableArray array];
    
    //3.打开数据库
    if ([db open]) {
        // 1.执行查询语句
        FMResultSet *resultSet = [db executeQuery:@"select  field_3, field_6, field_12 , field_13 from bb  "];

        @autoreleasepool {
              while ([resultSet next]) {
                  MAMultiPointItem *item = [[MAMultiPointItem alloc] init];
                  double  longitude= [resultSet doubleForColumn:@"field_12"];
                  double latitude = [resultSet doubleForColumn:@"field_13"];
                   NSString * name = [resultSet stringForColumn:@"field_3"];
                  NSString *address=[resultSet stringForColumn:@"field_6"];
                  CLLocationCoordinate2D newCoordinate =CLLocationCoordinate2DMake(latitude,longitude);
                  item.coordinate = newCoordinate;
                  item.title=name;
                  item.subtitle=address;
                  [items addObject:item];
                  
              }
        }
        
    }
    
    _overlay = [[MAMultiPointOverlay alloc] initWithMultiPointItems:items];
    [self.mapView addOverlay:_overlay];
    
    [self.mapView setVisibleMapRect:_overlay.boundingMapRect];
}

-(void)showBottomViewWithInfo:(MAMultiPointItem *)item{
    
    if(!bottomView){
        bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, self.view.bottom-150, self.view.width, 150)];
        bottomView.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:bottomView];
        
        nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(20, 0,bottomView.width-40 , 50)];
        nameLabel.font=[UIFont boldSystemFontOfSize:14.0f];
        nameLabel.textColor=[UIColor blackColor];
        [bottomView addSubview:nameLabel];
        
        positonlabe=[[UILabel alloc]initWithFrame:CGRectMake(20, nameLabel.bottom,bottomView.width-40 ,30)];
        positonlabe.font=[UIFont systemFontOfSize:12.0f];
        positonlabe.numberOfLines=2;
        positonlabe.textColor=[UIColor lightGrayColor];
        [bottomView addSubview:positonlabe];
       
        int width=(self.view.width/2);
        
        NSArray *titles=@[@"详细",@"导航"];
        for (int d=0; d<titles.count; d++) {
        UIButton *bt=[[UIButton alloc]initWithFrame:CGRectMake(20 + width*d, positonlabe.bottom+10, width-40 ,  40 )];
        [bt setTitle:titles[d] forState:UIControlStateNormal];
        [bt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.view addSubview:bt];
            bt.tag=1000+d;
        bt.backgroundColor=[UIColor lightGrayColor];
            [bt addTarget:self action:@selector(gotoannoattion:) forControlEvents:UIControlEventTouchUpInside];
           [bottomView addSubview:bt];
        }
        
    }
    if(item){
        currentSelectCharge=item;
        nameLabel.text=item.title;
        positonlabe.text=item.subtitle;
        
    }
    bottomView.hidden=false;
}
-(void)hiddenBottomView{
    bottomView.hidden=true;
}
-(void)gotoannoattion:(UIButton*)bt{
    if (bt.tag==1000) {
        [self showActionSheet];
    }else{
         [self showActionSheet];
    }
}
-(void)showActionSheet{
    // 创建
    
    UIAlertController *alertview=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    // UIAlertControllerStyleActionSheet 是显示在屏幕底部
    // UIAlertControllerStyleAlert 是显示在中间
    NSArray *titles=@[@"百度地图",@"高德地图",@"谷歌地图",@"腾讯地图"];
    NSArray *urls=@[@"baidumap://",@"iosamap://",@"comgooglemaps://",@"qqmap://"];
  

     for (int d=0; d<titles.count; d++) {
         if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urls[d]]]){
             UIAlertAction *defult = [UIAlertAction actionWithTitle:titles[d] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                baidumap://map/navi?location=40.057023,116.307852&coord_type=bd09ll&type=BLK&src=ios.baidu.openAPIdemo

                 NSDictionary *viaDic=@{@"viaPoints":@[@{@"name":@"北京西站",@"lat":[NSNumber numberWithDouble: 39.902463],@"lat":[NSNumber numberWithDouble:116.327737]}]};
                 NSError *error = nil;
                 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:viaDic
                                                                    options:kNilOptions
                                                                      error:&error];
                 
                 NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                              encoding:NSUTF8StringEncoding];
                 NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=%@&mode=driving&coord_type=gcj02&viaPoints=%@",self->currentSelectCharge.coordinate.latitude, self->currentSelectCharge.coordinate.longitude,@"目的地",jsonString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
             }];
                 [alertview addAction:defult];
         }
         
     }
    UIAlertAction *defult = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
       [alertview addAction:defult];
   
    [self presentViewController:alertview animated:YES completion:nil];
    
 
}
#pragma mark - Action Handlers

- (void)returnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - MAMapViewDelegate

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAMultiPointOverlay class]])
    {
        MAMultiPointOverlayRenderer * renderer = [[MAMultiPointOverlayRenderer alloc] initWithMultiPointOverlay:overlay];
        
        renderer.icon = [UIImage imageNamed:@"img_map_marker"];
        renderer.delegate = self;
        return renderer;
    }
    
    return nil;
}

- (void)mapView:(MAMapView *)mapView didAddOverlayRenderers:(NSArray *)overlayRenderers
{
    NSLog(@"overlayRenderers :%@", overlayRenderers);
}
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (!updatingLocation)
    {
        if(!didLocataion){
           
            didLocataion=true;
            MACoordinateSpan span=MACoordinateSpanMake(0.1, 0.1);
            MACoordinateRegion region=MACoordinateRegionMake(userLocation.location.coordinate, span);
            [mapView setRegion:region animated:YES];
        }
    }
    MAAnnotationView *userLocationView = [mapView viewForAnnotation:mapView.userLocation];
    [UIView animateWithDuration:0.1 animations:^{
        
        double degree = userLocation.heading.trueHeading - self.mapView.rotationDegree;
        userLocationView.imageView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f );
    }];
}
- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate{
   double timelast= [NSDate timeIntervalSinceReferenceDate];
    if(timelast-lastSelectChargeTime>0.1){
         [self hiddenBottomView];
    }
    NSLog(@"didSingleTappedAtCoordinate");
}

#pragma mark - MAMultiPointOverlayRendererDelegate

- (void)multiPointOverlayRenderer:(MAMultiPointOverlayRenderer *)renderer didItemTapped:(MAMultiPointItem *)item
{
    NSLog(@"item :%@ <%f, %f> name:%@", item, item.coordinate.latitude, item.coordinate.longitude,item);
    lastSelectChargeTime=[NSDate timeIntervalSinceReferenceDate];
    [self showBottomViewWithInfo:item];
}

@end
